<?php
class Application_Model_Seller
{
	private static $shopId = null;
	
	private function getShopid($userId){
		if(!self::$shopId){
			$shopTable = new Application_Model_DbTable_Shop();
			$result = $shopTable->checkShopInfo($userId);
			self::$shopId = $result['id'];
		}
		return self::$shopId;
	}
	
	public function deleteCategory($id, $totalLayer=3){
		$categoryIdRelationshipArray = array();
		$categoryIdsArray = array();
		$idsString = '0';
		$categoryTable = new Application_Model_DbTable_Category();
		$categorys = $categoryTable->getChildCategoryById($id);
		//return $categorys;
		if($categorys){
			$this->getChildCategoryId($categorys, $id, $categoryIdRelationshipArray, 1, $totalLayer);
			//return $categoryIdRelationshipArray;
			$parentIds = array();
			foreach ($categoryIdRelationshipArray as $value){
				foreach ($value as $subKey=>$subValue){
					$idsString .= ','.$subKey.','.$subValue;
					array_push($parentIds,$subKey);
					array_push($categoryIdsArray,$subValue);
				}
			}
			//return $categoryIdsArray;
			foreach ($categoryIdsArray as $key=>$value){
				if(in_array($value, $parentIds)){unset($categoryIdsArray[$key]);}
			}
		}else {
			$idsString .= ','.$id;
			array_push($categoryIdsArray, $id);
			//return $categoryIdsArray;
		}
		//$idsString .= '0';
		//return $categoryIdsArray;
		
		$goodsTable = new Application_Model_DbTable_Goods();
		foreach ($categoryIdsArray as $categoryId){
			$goods = $goodsTable->getGoodsByCategoryId($categoryId);
			if($goods){return false;}
		}
		
		//return $categoryTable->getDefaultAdapter()->query("DELETE FROM `myflower`.`fw_category` WHERE `fw_category`.`id` in ($idsString)")->execute();
		return $categoryTable->delete("id in ($idsString)");
		
	}
	
	private function getChildCategoryId($categorys, $parentId, &$categoryIdRelationshipArray, $currentlyLayer=1, $totalLayer){
		if(($currentlyLayer <= $totalLayer) && ($categorys)){
			foreach ($categorys as $key=>$value){
				//var_dump($parentId);
				array_push($categoryIdRelationshipArray, array($parentId=>$value['id']));
				$categoryTable = new Application_Model_DbTable_Category();
				$categorys = $categoryTable->getChildCategoryById($value['id']);
				++$currentlyLayer;
				$this->getChildCategoryId($categorys, $value['id'], $categoryIdRelationshipArray, $currentlyLayer, $totalLayer);
			}
		}
	}
	
	public function getGoodsList($userId){
		$shopId = $this->getShopid($userId);
		$categoryTable = new Application_Model_DbTable_Category();
		return $categoryTable->getCategorys($shopId);
	}
	
	public function addCategory($data){
		$shopId = $this->getShopid($data['user_id']);
		unset($data['user_id']);
		$data['shop_id'] = $shopId;
		$categoryTable = new Application_Model_DbTable_Category();
		return $categoryTable->insertCategory($data);
	}
}